package com.sunspring.jbug.support;

import com.sunspring.jbug.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;


/**
 * 邮件工具类
 * @author wulei
 * @date 2018-10-09
 **/
@Service
@Slf4j
public class EmailSupport {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String username;

    /**
      邮件默认标题
     */
    private static String subject = "Jbug系统";



    /**
     * 异步发送邮件
     * @param text 邮件正文
     * @param email 接收人email
     */
    @Async
    public void doSend(String text,String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(username);
        message.setTo(email);
        message.setText(text);
        message.setSubject(subject);
        try {
            javaMailSender.send(message);
            log.info("邮件发送成功,收件人：" + email);
        }catch (MailException ex) {
            log.error(ex.getMessage() + "邮件发送失败");
        }
    }

    /**
     * 发送重置密码的邮箱验证码
     * @param email email
     */
    public void verifyPwd(String email) {
        //生成随机验证码
        String verificationCode = CommonUtil.verificationCode();
        String text =  "验证码：" +
                verificationCode +
                "，有效期：" +
                LocalCache.duration + "分钟";
        //key->email,value->verificationCode存入缓存
        LocalCache.CACHE.put(email,verificationCode);
        doSend(text,email);
    }
}
